<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	class user extends CI_Controller {
		public function __construct()
		{
			parent::__construct();
			//$this->output->enable_profiler(TRUE);
			$this->load->helper('html');
			$this->load->helper('util');
			$this->load->helper('url');
			$this->load->library('form_validation');
			$this->load->library('ckeditor');
			$this->load->library('ckfinder');
			$this->load->model('admin/girl_model', 'girl_model');			
			$this->load->model('front/vote_model', 'vote_model');	
			session_start(); 
		}
		public function index()
		{
		}
		function array_random($arr, $num = 1) {
			shuffle($arr);
			
			$r = array();
			for ($i = 0; $i < $num; $i++) {
				$r[] = $arr[$i];
			}
			return $num == 1 ? $r[0] : $r;
		}
		public function allbum()
		{
			$data=$this->data();		
			$this->load->view('front/header_view',$data);
			$this->load->view('front/menu_view',$data);
			$this->load->view('front/allbum_view',$data);
			$this->load->view('front/menu_right_view',$data);
			$this->load->view('front/footer_view',$data);		
		}
		
		public function collection()
		{
			$result=$this->girl_model->get_list_all_girl();
			$data['result']=$result;		
			$this->load->view('front/header_view',$data);
			#$this->load->view('front/menu_view',$data);
			$this->load->view('front/allbum_view',$data);
			$this->load->view('front/footer_view',$data);	
		}
		function get_IP_address()
		{
			foreach (array('HTTP_CLIENT_IP',
				'HTTP_X_FORWARDED_FOR',
				'HTTP_X_FORWARDED',
				'HTTP_X_CLUSTER_CLIENT_IP',
				'HTTP_FORWARDED_FOR',
				'HTTP_FORWARDED',
				'REMOTE_ADDR') as $key){
					if (array_key_exists($key, $_SERVER) === true){
						foreach (explode(',', $_SERVER[$key]) as $IPaddress){
							$IPaddress = trim($IPaddress); // Just to be safe
							
							if (filter_var($IPaddress,
									FILTER_VALIDATE_IP,
									FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
								!== false) {
								
								return $IPaddress;
							}
						}
					}
				}
			}
			public function login_oauth()
			{
				$userAgent = $_SERVER['HTTP_USER_AGENT'];
				$start_time = MICROTIME(TRUE);
				$req_url = 'https://fpay.vn:443/oauth/request_token';
				$authurl = 'https://fpay.vn:443/oauth/authorize';
				$acc_url = 'https://fpay.vn:443/oauth/access_token';        
				//Your Application key and secret
				$conskey = 'D3vYB3c9toJDp4B8ZNS4vwMRfSrDRo7S';
				$conssec = 'FruMqNVjtAgnqt9SezJWzGhkJsUVrytw';
				$api_url = 'https://fpay.vn/rest';
				try {
					//	echo phpinfo();die;
					//create a new Oauth request
					$oauth = new OAuth($conskey, $conssec, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
					$oauth->enableDebug();
					$oauth->disableSSLChecks();	
					if(!isset($_GET['oauth_token']) || $_GET['oauth_token']=="" || !$_SESSION['state']) {
						
						$request_token_info = $oauth->getRequestToken($req_url);
						$request_token_info = utf8_encode(json_encode($request_token_info));
						$request_token_info = str_replace('\ufeff','',$request_token_info);
						$request_token_info = json_decode($request_token_info);
						
						$_SESSION['secret']= $request_token_info->oauth_token_secret;    
						$_SESSION['state']= 1;

						$uri=  $authurl.'?oauth_token='.$request_token_info->oauth_token;
						
						print_r('<iframe src="'.$uri.'" width="400" height="350"></iframe>');
						die;
						
					} else if($_SESSION['state']==1) {
						
						$oauth->setToken($_GET['oauth_token'], $_SESSION['secret']);
						$access_token_info = $oauth->getAccessToken($acc_url); 
						
						$access_token_info = utf8_encode(json_encode($access_token_info));    
						$access_token_info = str_replace('\ufeff','',$access_token_info);    	
						$access_token_info = json_decode($access_token_info);
						$_SESSION['state']= 2;
						$_SESSION['token']= $access_token_info->oauth_token;
						$_SESSION['secret']= $access_token_info->oauth_token_secret;  
						
						$oauth->setToken( $_SESSION['token'], $_SESSION['secret']);           
						$oauth->fetch("$api_url/me.json"); 	
						$result = str_replace("﻿","", $oauth->getLastResponse());
						$json = json_decode($result);
						$username = $json->name;
						$mail = $json->mail;
						$_SESSION['uname']=$username;
						$_SESSION['uid']=$json->uid;
						
						$_SESSION['count_vote']=$this->vote_model->vote_user_count($json->uid);
						$_SESSION['count_not_vote']=$this->config->item('count_vote')-$this->vote_model->vote_user_count($json->uid);
						
						$_SESSION['key_login']=md5($this->config->item('key_login'));
						$_SESSION['user_data']= $json;        
						log_message('info', "157: log oauth:  Time = ".(MICROTIME(TRUE) -  $start_time)." login thanh cong ".$username.":".$json->uid." ip:".$this->get_IP_address()." ".$userAgent);
						
						if(isset($_GET['login']))
						{
							if(!isset($_SESSION['count_login']))
							{                        
								$_SESSION['count_login']=1;                         
								echo "<script>   
									parent.window.location.reload();            
									parent.jQuery.fancybox.close();    		         
									</script>"; 
							}
						}
						else
						{
							echo "<script>   
								parent.window.location.reload();            
								parent.jQuery.fancybox.close();    		         
								</script>"; 
						}
					}
					else
					{
						
					} 				

				} catch(OAuthException $E) {
					echo ' 
						<script> 
						alert("Đăng nhập thất bại");   
						parent.window.location.reload();            
						parent.jQuecybox.close();    
						
						</script>';
				}
			}
			public function logout()
			{
				session_destroy();				
				$uri='https://fpay.vn/user/logout';	
				print_r('<div style="margin:auto; width:200px; height:90px;">Xin chờ thực hiện trong giây lát ... 
						<iframe style="display:none" src="'.$uri.'" ></iframe>></div>');
				
				echo "<script>   
					setTimeout(function()
					{ reload(); }, 1500);
					function reload()
					{
					parent.window.location.reload();            
					parent.jQuery.fancybox.close();   
					} 		         
					</script>";
				die;
			}
			
			public function vote()
			{
				
				if(!isset($_SESSION['uid']))
				{       
					echo -2;
				}	
				else
				{
					$data['uid']=$_SESSION['uid'];
					$data['gid']=$_SESSION['gid'];
					$errorCode = $this->vote_model->vote($data);
					if(isset($errorCode))
					{
						echo $errorCode;
					}
					else
					{
					   echo -3;
					}
				}
			}
            
            public function data()
            {
                 $menu=$this->girl_model->get_list_all_girl();
    			if(!isset($_GET['gid']))
    			{
    				$data_id=array();
    				$i=0;
    				foreach($menu as $row)
    				{$i++;
    					$data_id['id'.$i]=$row->gid;
    				}				
    				$id = $this->array_random($data_id);
    			}
    			else
    			{
    				$id=$_GET['gid'];	
    			}
    			$_SESSION['gid']=$id;
    			//random cô được chọn
    			$result=$this->girl_model->get_girl_by_id($id);
    			if($result!=null)
    			{
    				$data['result']=$result;	
    			}	
    			
    			$data['menu']=$menu;
    			//Kiểm tra ngày này đã bình chọn uid này chưa	
    			if(isset( $_SESSION['uid']))
    			{
    				$data['uid']=$_SESSION['uid'];
    				$data['gid']=$id;	
    				$data['vote']=$this->vote_model->check_vote($data);
                    $_SESSION['count_vote']=$this->vote_model->vote_user_count($_SESSION['uid']);
        			$_SESSION['count_not_vote']=$this->config->item('count_vote')-$_SESSION['count_vote'];
        			if(	$_SESSION['count_vote']==$this->config->item('count_vote'))
        			{
        				$_SESSION['count_not_vote']="Đã hết";
        			}
    			}
    			else
    				$data['vote']=2;
                    
                    
                $data['count_girl_vote']=$this->vote_model->vote_girl_count($_SESSION['gid']);
                return $data;
            }
            
            public function the_le()
            {
           	  
		        $data=$this->data();
               	$this->load->view('front/header_view',$data);
    			$this->load->view('front/menu_view',$data);
    			$this->load->view('front/the_le_view',$data);
    			$this->load->view('front/menu_right_view',$data);
			    $this->load->view('front/footer_view',$data);
            }
            
            public function giai_thuong()
            {
                $data=$this->data();
               	$this->load->view('front/header_view',$data);
    			$this->load->view('front/menu_view',$data);
    			$this->load->view('front/the_le_view',$data);
    			$this->load->view('front/menu_right_view',$data);
			    $this->load->view('front/footer_view',$data);
            }
            
              public function luot_vote()
            {
                $data=$this->data();
               	$this->load->view('front/header_view',$data);
    			$this->load->view('front/menu_view',$data);
                if(isset( $_SESSION['uid']))
    			{
                 $data['list_vote']  = $this->vote_model->list_vote_user($_SESSION['uid']);
                 //print_r($data['list_vote']);die;
                }
    			$this->load->view('front/luot_vote_view',$data);
    			$this->load->view('front/menu_right_view',$data);
			    $this->load->view('front/footer_view',$data);
            }
            
		}
